package com.jml;


import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.AttributeKey;
import java.nio.charset.Charset;

/**
 * @author:jml
 * @date: 2019/9/23 17:50
 * @description：Netty客户端的构建
 */
public class NettyClient {

	public static void main(String[] args) {
		EventLoopGroup group = new NioEventLoopGroup();
		try {
			Bootstrap bootstrap = new Bootstrap();
			//设置通道
			bootstrap.channel(NioSocketChannel.class);
			bootstrap.group(group);
			bootstrap.option(ChannelOption.SO_KEEPALIVE, true)
					.handler(new ChannelInitializer<NioSocketChannel>() {
						@Override
						protected void initChannel(NioSocketChannel ch) throws Exception {
							//Delimiters.lineDelimiter()[0]表示分隔符

							//解码器
							ch.pipeline().addLast(new DelimiterBasedFrameDecoder
									(Integer.MAX_VALUE,Delimiters.lineDelimiter()[0]));

							//加一个解码器
							ch.pipeline().addLast(new StringDecoder());
							
							ch.pipeline().addLast(new ClientHandler());

							//加一个编码器
							ch.pipeline().addLast(new StringEncoder());
						}
					});

			ChannelFuture future = bootstrap.connect("localhost", 8080).sync();

			String person = "张三\r\n";

			ByteBuf buffer = PooledByteBufAllocator.DEFAULT.buffer();
			buffer.writeBytes(person.getBytes(Charset.defaultCharset()));

			//future.channel().write(person.getBytes(Charset.forName("UTF-8")));

			//future.channel().writeAndFlush(Delimiters.lineDelimiter()[0]);
			
			future.channel().writeAndFlush(person);

			future.channel().closeFuture().sync();
			
			Object channelKey = future.channel().attr(AttributeKey.valueOf("ChannelKey")).get();
			System.out.println(channelKey+"-x-x-x");
			
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			group.shutdownGracefully();
		}


	}
}
